import pygame
import cPickle as pickle
import traceback
import sys


class HackedGroup(pygame.sprite.Group):

    def get_extra_objects(self):
        return None

    def dump(self, fname):

        pickleObj = []

        for n in self.sprites():
            try:
                d = n.load()
                e = n.pickle_obj()
                pickleObj.append((d, e))
            except AttributeError:
                print "Couldn't pickle object - " + str(n)

        d = self.get_extra_objects()

        if d:
            pickleObj.append(d)

        f = open(fname, "w")
        pickle.dump(pickleObj, f)
        f.close()

    def load(self, fname):

        f = open(fname, "r")
        data = pickle.load(f)
        f.close()

        for _load, pickle_obj in data:
            try:
                spr = _load(pickle_obj)
                if spr:
                    self.add(spr)
            except:
                print sys.exc_info()

    def get_object(self, _type):
        for n in self.sprites():
            if type(n) == _type:
                return n


class WallGroup(HackedGroup):

    def __init__(self, owner, *sprites):
        HackedGroup.__init__(self, sprites)
        self.owner = owner

    def load(self, fname):

        f = open(fname, "r")
        data = pickle.load(f)
        f.close()

        for _load, pickle_obj in data:
            try:
                spr = _load(self.owner, pickle_obj)
                if spr:
                    self.add(spr)
            except:
                f = open("crash.log", "w")
                traceback.print_tb(sys.exc_traceback, file=f)
                f.close()
                print sys.exc_info()
